<template>
  <div
    class="flex"
    style="font-family: PingFang SC; font-weight: 300; font-size: 14px; color: #000000"
  >
    账号信息
  </div>
  <div class="h-[372px] flex flex-col items-center">
    <!-- 用户信息卡片 -->
    <div
      class="w-[350px] h-[140px] bg-gray-100 font-pingfang font-light text-black rounded-md mt-3 flex items-center"
    >
      <div class="user-info flex items-center gap-3 ml-6 select-none">
        <div class="relative">
          <div
            class="absolute bottom-0 w-12 h-3 text-[9px] bg-black/50 text-center rounded-sm text-white cursor-pointer z-10 select-none leading-tight"
            style="-webkit-text-stroke: thin; letter-spacing: 3px; text-indent: 3px"
          >
            修改
          </div>
          <Avatar
            class="w-[18px] h-[18px]"
            shape="square"
            :size="48"
            :src="userStore.userData?.user?.headimgurl || NavUser"
            style="filter: invert(1)"
          >
            <template #icon><UserOutlined /></template>
          </Avatar>
        </div>
        <div>
          <p class="text-lg select-text">{{ userStore.userData?.user.realname }}</p>
          <p class="text-sm select-text">{{ userStore.userData?.user.mobile }}</p>
        </div>
      </div>
    </div>

    <!-- 自动登录和重设密码 -->
    <div class="mt-3 text-sm select-none">
      <Checkbox v-model:checked="autoLogin" @change="() => userStore.setAutoLoginAction(autoLogin)">
        自动登录
      </Checkbox>
      <div class="inline ml-8 cursor-pointer" @click="() => (resetPwd = !resetPwd)">
        <img class="inline w-3.5 h-3.5 -mt-0.5" :src="Warning" />
        <span class="ps-2">重设密码</span>
      </div>
    </div>

    <!-- 密码表单 -->
    <div v-if="resetPwd" class="w-full flex flex-col items-center gap-4 mt-3">
      <Form
        ref="formRef"
        name="custom-validation"
        :model="formState"
        :rules="rules"
        v-bind="layout"
      >
        <FormItem has-feedback name="pass">
          <InputPassword
            class="w-[165px] h-[27px] rounded-none focus:border-primary focus:shadow-[0_0_0_2px_rgba(3,14,21,0.14)] hover:border-primary focus:hover:border-primary"
            v-model:value="formState.pass"
            placeholder="请输入登陆密码"
            :maxlength="18"
            autocomplete="off"
          />
        </FormItem>
        <FormItem has-feedback name="checkPass">
          <InputPassword
            class="w-[165px] h-[27px] rounded-none focus:border-primary focus:shadow-[0_0_0_2px_rgba(3,14,21,0.14)] hover:border-primary focus:hover:border-primary"
            v-model:value="formState.checkPass"
            placeholder="请再次输入登陆密码"
            :maxlength="18"
            :visibilityToggle="false"
            autocomplete="off"
          />
          <AButton
            class="w-[41px] h-[27px] rounded-[5px] absolute bg-primary text-white text-[11px] ml-2 px-2.5 py-1"
            type="primary"
            @click="handleResetPassword"
          >
            重设
          </AButton>
        </FormItem>
      </Form>
    </div>

    <!-- 退出登录按钮 -->
    <div class="mt-4 text-sm">
      <AButton class="bg-gray-200 text-black text-sm" type="primary" @click="handleLogout">
        退出登录
      </AButton>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { UserOutlined } from '@ant-design/icons-vue';
import NavUser from '@main/assets/images/layout-nav-user.webp';
import Warning from '@main/assets/images/workflow/warning.webp';
import { useUserStore } from '@shared/store/user';
import { Form, FormItem, Avatar, InputPassword, Checkbox, message } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import type { FormInstance } from 'ant-design-vue';
import { changePwdApi } from '@main/service/setting';
import type { changePwdReq } from '@main/service/setting/type';

interface FormState {
  pass: string;
  checkPass: string;
}

const formRef = ref<FormInstance>();
const userStore = useUserStore();
const autoLogin = ref(
  (() => {
    return userStore.userSetting?.autoLogin || false;
  })()
);
const resetPwd = ref(false);

const formState = reactive<FormState>({
  pass: '',
  checkPass: ''
});

const validatePass = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入密码');
  } else if (value.length < 6) {
    return Promise.reject('密码长度不能低于6位');
  } else {
    if (formState.checkPass !== '') {
      formRef.value?.validateFields('checkPass');
    }
    return Promise.resolve();
  }
};

const validatePass2 = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请再次输入密码');
  } else if (value !== formState.pass) {
    return Promise.reject('二次输入不一致');
  } else {
    return Promise.resolve();
  }
};

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 }
};

const rules: Record<string, Rule[]> = {
  pass: [{ required: true, validator: validatePass, trigger: 'change' }],
  checkPass: [{ validator: validatePass2, trigger: 'change' }]
};

const handleResetPassword = () => {
  changePwdApi({ password: formState.pass } as changePwdReq)
    .then(() => {
      message.success('密码修改成功');
      const persistLoginAccountData = userStore.getLocalPersistLoginAccountData();
      if (persistLoginAccountData) {
        persistLoginAccountData.password = formState.pass;
        userStore.saveLocalPersistLoginAccountData(persistLoginAccountData);
      }
    })
    .finally(() => {
      formState.pass = '';
      formState.checkPass = '';
    });
};

const handleLogout = () => {
  window.clientAppSdk.ipc.ipcRenderer.send('rc:childWindow', 'logout');
};
</script>
<style lang="less" scoped>
:deep(.ant-form-item) {
  margin-bottom: 9px;
}
</style>
